//
//  CTContactHelper.m
//  CT
//
//  Created by liufanwei on 15/4/8.
//  Copyright (c) 2015年 liufanwei. All rights reserved.
//

#import "CTContactManager.h"
#import "BDKNotifyHUD.h"
#import "CTContactShowItem.h"
#import "CommonMicro.h"

@interface CTContactManager(){
    CFArrayRef _ArrayRef;
    NSMutableArray * _ArrAyData;
}

@end

@implementation CTContactManager

+(CTContactManager*)share{
    static dispatch_once_t onceToken;
    static CTContactManager * helper;
    dispatch_once(&onceToken, ^{
        helper = [[CTContactManager alloc] init];
    });
    return helper;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        _ArrAyData = [[NSMutableArray alloc] init];
    }
    return self;
}

-(CFArrayRef)ContactRef{
    return _ArrayRef;
}

-(NSArray*)ContactArr{
    return _ArrAyData;
}

-(NSArray*)ContactArrWithFilter:(NSString*)filterStr{
    NSMutableArray * arr = [[NSMutableArray alloc] init];
    for (CTContactShowItem * item in _ArrAyData) {
        NSString * name = item.Name;
        if (name == Nil || name.length == 0) {
            continue;
        }
        NSRange range = [name rangeOfString:filterStr];
        if (range.length != 0) {
            [arr addObject:item];
        }
        NSString * phoneNumber = item.PhoneNumber;
        if (phoneNumber == Nil || phoneNumber.length == 0) {
            continue;
        }
        range = [phoneNumber rangeOfString:filterStr];
        if (range.length != 0) {
            [arr addObject:item];
            continue;
        }
        NSString * pinyin = item.PingYing;
        range = [pinyin rangeOfString:filterStr];
        if (range.length != 0) {
            [arr addObject:item];
            continue;
        }
    }
    return arr;
}


-(void)reload{
    [_ArrAyData removeAllObjects];
    _ArrayRef = Nil;
    CFErrorRef error;
    ABAddressBookRef result = ABAddressBookCreateWithOptions(NULL, &error);
    if (!result)
    {
        NSLog(@"get addressBook failed:%@", error);
        return;
    }
    
    ABAddressBookRequestAccessWithCompletion(result, ^(bool granted, CFErrorRef error) {
        if (!granted) {
            [BDKNotifyHUD notifyHUDWithText:@"获取通信录失败"];
            return;
        }
        _ArrayRef = ABAddressBookCopyArrayOfAllPeople(result);
        
        for (NSInteger i = 0; i < CFArrayGetCount(_ArrayRef); i++) {
            CTContactShowItem * item = [self converToShowData:i];
            if (item) {
                [_ArrAyData addObject:item];
            }
        }
        if(_callback){
            _callback(self);
        }
    });
    
}

-(NSInteger)ContactLength{
    return CFArrayGetCount(_ArrayRef);
}

-(CTContactShowItem*)converToShowData:(NSInteger)i{
    CTContactShowItem * item = [CTContactShowItem create];
    //读取firstname
    ABRecordRef person = CFArrayGetValueAtIndex(_ArrayRef, i);

    NSString * firstName  = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonFirstNameProperty));
    if (firstName) {
        item.Name = firstName;
    }
    NSString * middleName = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonMiddleNameProperty));
    if (middleName) {
        item.Name = [NSString stringWithFormat:@"%@%@",item.Name,middleName];
    }
    NSString * lastName   = (NSString*)CFBridgingRelease(ABRecordCopyValue(person, kABPersonLastNameProperty));
    if (lastName) {
        item.Name = [NSString stringWithFormat:@"%@%@",item.Name,lastName];
    }
    
    CFDataRef headData = ABPersonCopyImageData(person);
    if (headData) {
        item.ImageData = (__bridge NSData*)headData;
//        NSLog(@"获取头像成功%@",item.Name);
    }
    
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    NSString * number = [NSString string];
    for (int k = 0; k<ABMultiValueGetCount(phone); k++)
    {
        NSString * personPhone = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, k));
        number = personPhone;
    }
    ABRecordID recordId = ABRecordGetRecordID(person);
    item.Cid = [NSString stringWithFormat:@"%d",recordId];
    
    item.PhoneNumber = [number stringByReplacingOccurrencesOfString:@"-" withString:@""];
    NSMutableString *source = [item.Name mutableCopy];
    if (source) {
        CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformMandarinLatin, NO);
        CFStringTransform((__bridge CFMutableStringRef)source, NULL, kCFStringTransformStripDiacritics, NO);
        item.PingYing = source;
        NSString * key = [item.PingYing substringToIndex:1];
        item.SortStr = [key uppercaseString];
        return item;
    }
    
    return Nil;
}

-(CTContactShowItem*)ContactWithPhoneNumber:(NSString*)phoneNumber{
    for (CTContactShowItem * item in _ArrAyData) {
        if ([item.PhoneNumber isEqualToString:phoneNumber]) {
            return item;
        }
    }
    return Nil;
}
@end
